<?php

namespace App\Console\Commands;

use App\Api\Models\LogInStorageModel;
use App\V3\V3_2_6\Models\LogOutStorageModel;
use App\V3\V3_2_6\Models\StorageShelfLocationModel;
use App\V3\V3_2_6\Models\StorageShelfModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class UpdateLogShelf extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'LogShelf:updateData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新相关表数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        set_time_limit(0);
        @ini_set('memory_limit', '1024M');

        self::updateInLog();
//        self::updateOutLog();

        return true;
    }

    public function common($list)
    {
        $data = [];
        foreach($list as $value) {
            $shelfInfo = StorageShelfModel::query()->where([
                'storage_id' => $value->storage_id,
                'shelf_type' => 1
            ])->first();

            if(!empty($shelfInfo)) {
                $shelfId = $shelfInfo->id;
            }
            else {
                $shelfId = 0;
            }

            if($shelfId == 0) {
                $locationId = 0;
            }
            else {
                $locationInfo = StorageShelfLocationModel::query()
                    ->where([
                        'shelf_id'=>$shelfInfo['id'],
                        'location_type' => 1
                    ])
                    ->first();

                $locationId = $locationInfo->id;
            }

            $data[] = [
                'id' => $value->id,
                'shelf_id' => $shelfId,
                'location_id' => $locationId
            ];
        }

        return $data;
    }

    public function updateInLog()
    {
        $list = LogInStorageModel::query()->where(['delete_flag' => 0])
            ->where('shelf_id', '!=', 0)
            ->where('location_id', '!=', 0)
            ->get();

        if(!empty($list)) {
            if(!empty($data = self::common($list))) {
                batch()->update(new LogInStorageModel, $data, 'id');
            }
        }

        return true;
    }

    public function updateOutLog()
    {
        $list = LogOutStorageModel::query()->where(['delete_flag' => 0])
            ->where('shelf_id', '!=', 0)
            ->where('location_id', '!=', 0)
            ->get();

        if(!empty($list)) {
            if(!empty($data = self::common($list))) {
                batch()->update(new LogOutStorageModel, $data, 'id');
            }
        }

        return true;
    }
}
